package com.tool.payment.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;

public class HttpRequest {
	
	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(HttpRequest.class);

	/**
     * 下载文件
     * @param requestUrl
     * @param filepath
     * @param type
     */
    public static File downFile(String requestUrl,String filepath,String outputStr) {
    	File file = new File(filepath);
    	if(!file.getParentFile().exists()) {
    		file.getParentFile().mkdirs();
    	}
    	if(!file.exists()) {
    		try {
				file.createNewFile();
			} catch (IOException e) {
			}
    	}
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setRequestProperty("Cache-Control", "no-cache");
            httpUrlConn.setRequestProperty("Content-Type", "text/xml");
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod("GET");
            
            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            
            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
        	BufferedInputStream bis = new BufferedInputStream(inputStream);
            
			byte[] buf = new byte[1024];
			OutputStream fileOut = new FileOutputStream(file);
			int size = 0;
			while ((size = bis.read(buf)) != -1) {
				fileOut.write(buf, 0, size);  
			}
			fileOut.flush();
			fileOut.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
        } catch (ConnectException ce) {
        	ce.printStackTrace();
            logger.error("Weixin server connection timed out.");
        } catch (Exception e) {
        	e.printStackTrace();
            logger.error("https request error:{}", e);
        }
        return file;
    }
	
    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String xmlInfo) {
		String result = "";
    	try {
            URL conUrl = new URL(url);
            URLConnection con = conUrl.openConnection();
            con.setDoOutput(true);
            con.setRequestProperty("Cache-Control", "no-cache");
            con.setRequestProperty("Content-Type", "text/xml");

            OutputStreamWriter out = new OutputStreamWriter(con
                    .getOutputStream());    
            
            out.write(new String(xmlInfo.toString().getBytes(), "utf-8"));
            out.flush();
            out.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(con
                    .getInputStream(), "utf-8"));
            String line = "";
            for (line = br.readLine(); line != null; line = br.readLine()) {
            	result+=line;
            }
            br.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
    	
    	return result;
    }
    
    public static String requestToString(HttpServletRequest request) throws IOException {

    	BufferedReader  br = request.getReader();
    	StringBuilder result = new StringBuilder();
    	String line="";
    	 while ((line = br.readLine()) != null) {
    		 result.append(line);
    	    }
        return result.toString();
    }
}
